package com.dwxt.community.service;

import com.dwxt.common.base.*;
import com.dwxt.common.util.*;
import com.dwxt.community.dao.*;
import com.dwxt.community.entity.*;
import com.dwxt.community.service.feign.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.*;

import java.io.*;
import java.text.*;
import java.util.*;

@Service
public class SmsService {


    @Autowired
    private UserService userService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private RecoveryOndoorMapper recoveryOndoorMapper;
    @Autowired
    private RecycleAddressMapper recycleAddressMapper;

    /**
     * 上门回收短信发送
     *
     * @param recycleRecord
     * @return
     */
    public BaseResult sendSms(RecycleRecord recycleRecord) {
        User user = userService.selectCurrUserByPrimaryKey();
        //日期转换
        Date appointTime = recycleRecord.getAppointTime();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(appointTime);
        //查询回收员电话
        RecoveryOndoorExample recoveryOndoorExample = new RecoveryOndoorExample();
        recoveryOndoorExample.createCriteria().andCommunityIdEqualTo(recycleRecord.getCommunityId());
        List<RecoveryOndoor> recoveryOndoorsList = recoveryOndoorMapper.selectByExample(recoveryOndoorExample);

        if (recoveryOndoorsList.size() == 1) {
            try {
                //短信内容
                String postData="您的订单编码：【预约时间:"+dateString+","+"地址:"+recycleRecord.getRecycleAddress()+"电话:"+recycleRecord.getPhone()+"】。如需帮助请联系客服。";
                //上门回收人员电话
                postData = "account=ZTCQ888&password=ZTCQ888&mobile=" + recoveryOndoorsList.get(0).getPhone() + "&content=" + java.net.URLEncoder.encode(postData, "utf-8");
                return SmsUtil.SMS(postData);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        return BaseResult.build(StatusCode.SMS_UNKNOWN);
    }

    /**
     * 用户注册短信发送
     *
     * @param phoneNum
     * @return
     */
    public BaseResult sendCaptcha(String phoneNum) {
        String captcha = ValidCodeUtils.generateNumber(4);
        try {
            String postData = "您的验证码是：【" + captcha + "】。请不要把验证码泄露给其他人。如非本人操作，可不用理会！";
            postData = "account=ZTCQ888&password=ZTCQ888&mobile=" + phoneNum + "&content=" + java.net.URLEncoder.encode(postData, "utf-8");
            //验证码5分钟有效
            redisService.set(phoneNum, captcha, (long) 300 * 10);
            return SmsUtil.SMS(postData);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return BaseResult.build(StatusCode.SMS_UNKNOWN);
    }

}
